package com.ley.yikang.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.ley.yikang.entity.Admin;
import com.ley.yikang.entity.Child;
import com.ley.yikang.entity.Doctor;
import com.ley.yikang.entity.Elder;

import java.util.Date;

public class TokenUtil {
    public static String getChildToken(Child child) {
        Date start = new Date();
        long currentTime = System.currentTimeMillis() + 60 * 60 * 1000 * 96;//四天有效时间
        Date end = new Date(currentTime);
        String token;

        token = JWT.create().withAudience(String.valueOf(child.getId()), "child").withIssuedAt(start).withExpiresAt(end)
                .sign(Algorithm.HMAC256(child.getPassword()));
        return token;
    }

    public static String getElderToken(Elder elder) {
        Date start = new Date();
        long currentTime = System.currentTimeMillis() + 60 * 60 * 1000 * 96;//四天有效时间
        Date end = new Date(currentTime);
        String token;

        token = JWT.create().withAudience(String.valueOf(elder.getId()), "elder").withIssuedAt(start).withExpiresAt(end)
                .sign(Algorithm.HMAC256(elder.getPassword()));
        return token;
    }

    public static String getDoctorToken(Doctor doctor) {
        Date start = new Date();
        long currentTime = System.currentTimeMillis() + 60 * 60 * 1000 * 96;//四天有效时间
        Date end = new Date(currentTime);
        String token;

        token = JWT.create().withAudience(String.valueOf(doctor.getId()), "doctor").withIssuedAt(start).withExpiresAt(end)
                .sign(Algorithm.HMAC256(doctor.getPassword()));
        return token;
    }

    public static String getAdminToken(Admin admin) {
        Date start = new Date();
        long currentTime = System.currentTimeMillis() + 60 * 60 * 1000 * 96;//四天有效时间
        Date end = new Date(currentTime);
        String token;

        token = JWT.create().withAudience(String.valueOf(admin.getId()), "admin").withIssuedAt(start).withExpiresAt(end)
                .sign(Algorithm.HMAC256(admin.getPassword()));
        return token;
    }


    public static int getTokenUserId(String token) {
        return Integer.parseInt(JWT.decode(token).getAudience().get(0));
    }

    public static String getTokenUserType(String token) {
        return JWT.decode(token).getAudience().get(1);
    }
}
